package TinTuc;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.*;
import org.jdom2.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author PeSu
 */
public class GUI extends javax.swing.JFrame implements TreeSelectionListener {

    public static List<Article> ds;
    public static ArrayList list;
    public static MutableTreeNode root;
    public static DefaultTreeModel model;
    private static int iPage;

    @Override
    public void valueChanged(TreeSelectionEvent tse) {
        TreeNode temp = (TreeNode) tree1.getLastSelectedPathComponent();
        if (temp != null) {
            TN = temp;

        }
    }

    /**
     * Creates new form GUI
     */
    public GUI() {
        initComponents();
        File folder = new File("data");
        if (!(folder.exists() && folder.isDirectory())) {
            //JOptionPane.showMessageDialog(lHinh, "Chua co data");
            folder.mkdir();

        }
        folder = new File("temp");
        if (!(folder.exists() && folder.isDirectory())) {
            //JOptionPane.showMessageDialog(lHinh, "Chua co data");
            folder.mkdir();

        }
        File f = new File("cautrucxpathcuatrangweb.xml");
        if (!f.exists()) {
            try {
                XPathWriter xw = new XPathWriter();
                xw.Write();
            } catch (JDOMException ex) {
                Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        CreateTree();        LoadTreeNode();
        iPage = 1;
        lbtrang.setText(iPage + "");


    }

    private void AddWeb(TreeNode root, String domain) {
        try {
            MutableTreeNode r = (MutableTreeNode) root;
            MutableTreeNode subnode = new DefaultMutableTreeNode(domain);
            r.insert(subnode, 0);
            model = new DefaultTreeModel(this.root);
            this.tree1.setModel(model);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(lHinh, "Chưa chọn Root <WEB>" + ex.getMessage());
        }
    }

    private void CreateTree() {
        //DefaultMutableTreeNode root = new DefaultMutableTreeNode("Web");
        //DefaultMutableTreeNode aNode = new DefaultMutableTreeNode("http://vnexpress.net/");
        root = new DefaultMutableTreeNode("Web");

        model = new DefaultTreeModel(root);
        this.tree1.setModel(model);
    }

    private void AddTree(String url) {
        MutableTreeNode gears = new DefaultMutableTreeNode(url);

        this.tree1.addPropertyChangeListener(url, null);
    }

    private void LoadTreeNode() {
        try {
            File fi = new File("data");
            ArrayList tre = new ArrayList();
            if (fi.exists()) {
                String s[] = fi.list();
                String node;
                for (int i = 0; i < s.length; i++) {
                    node = s[i].substring(0, s[i].length() - 4);
                    tre.add(node);
                }
            }
            for (int i = 0; i < tre.size(); i++) {
                String node = tre.get(i).toString();
                AddWeb(GUI.root, node);
            }
            for (int i = 0; i < GUI.root.getChildCount(); i++) {
                TreeNode t = root.getChildAt(i);
                File fi2 = new File("data/" + t.toString() + ".xml");
                ArticleReader ar = new ArticleReader(fi2);
                List<Element> lst = ar.LayChuyenmuc();
                for (int j = 0; j < lst.size(); j++) {
                    AddWeb(t, lst.get(j).getAttributeValue("name"));
                }
            }
        } catch (Exception ex) {
        }
    }
  
    private boolean NhayTrang(String tenfile, String chuyenmuc, int target) {
        try {
            DefaultTableModel tablemodle;
            String[] columnNames = {"Title", "Link", "Date"};
            Object[][] data = null;
            tablemodle = new DefaultTableModel(data, columnNames);
            File fi = new File(tenfile);
            ArticleReader ar = new ArticleReader(fi);
            ds = ar.Read(chuyenmuc, target);
            
            for (int i = 0; i < ds.size(); i++) {
                String link = ds.get(i).getLink();
                Object[] newRowData = {ds.get(i).getTitle(), link, ds.get(i).getDate()};
                tablemodle.addRow(newRowData);
            }
           
            this.tbTin.setModel(tablemodle);
            
            if (ds.size() <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
        }
        return false;

    }

    private void ListItem(String tenfile, String chuyenmuc, int[] pages) {
        try {
            DefaultTableModel tablemodle;
            String[] columnNames = {"Title", "Link", "Date"};
            Object[][] data = null;
            tablemodle = new DefaultTableModel(data, columnNames);
            File fi = new File(tenfile);
            ArticleReader ar = new ArticleReader(fi);
            for (int j = 1; j <= pages.length; j++) {
                ds = ar.Read(chuyenmuc, j);
                for (int i = 0; i < ds.size(); i++) {
                    String link = ds.get(i).getLink();
                    Object[] newRowData = {ds.get(i).getTitle(), link, ds.get(i).getDate()};
                    tablemodle.addRow(newRowData);
                }
            }
//        for(int i=0;i<n;i++)
//        {
//           Object[] newRowData={listpeer.get(i).getID(),listpeer.get(i).getAddress(),listpeer.get(i).getPort()};
//           tablemodle.addRow(newRowData);
//        }
            this.tbTin.setModel(tablemodle);
        } catch (Exception ex) {
        }
    }

    private void loadTin(List<Article> ds, int i) {
        try {
            this.lblTitle.setText(ds.get(i).getTitle());
            this.lbNgayDang.setText("Ngày đăng: "+ds.get(i).getDate());
            String text1 = ds.get(i).getSummary();
            String text[] = text1.split("   ");
            this.txtSummary.setText(text[0]);
            String urlimage=ds.get(i).getImg();
            if(!urlimage.startsWith("http://"))
            {
                urlimage="http://"+TN.getParent().toString()+urlimage;
            }
            BufferedImage img = ImageIO.read(new URL(urlimage));
            ImageIcon a = new ImageIcon(img);
            Image imge = a.getImage();
            Image newimg = img.getScaledInstance(this.lHinh.getWidth(), this.lHinh.getHeight(), java.awt.Image.SCALE_SMOOTH);
            a = new ImageIcon(newimg);
            this.lHinh.setIcon(a);
            
        } catch (Exception ex) {
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtURL = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tree1 = new javax.swing.JTree();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tbTin = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        lblTitle = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtSummary = new javax.swing.JTextArea();
        lHinh = new javax.swing.JLabel();
        lbNgayDang = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        btnnext = new javax.swing.JButton();
        btnpre = new javax.swing.JButton();
        lbtrang = new javax.swing.JLabel();
        lbtongtrang = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        btncauHinhXPath = new javax.swing.JButton();
        btnThemChuyenMuc = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("URL:");

        txtURL.setText("http://vtc.vn/");
        txtURL.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtURLActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/TinTuc/image/AddItem.png"))); // NOI18N
        jButton4.setToolTipText("Thêm tin trang web mới");
        jButton4.setName("btnAdd"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setToolTipText("");

        tree1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tree1MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tree1);
        tree1.getSelectionModel().addTreeSelectionListener(this);
        tree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tbTin.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Title", "Link", "Date"
            }
        ));
        tbTin.setAlignmentX(1.0F);
        tbTin.setAlignmentY(1.0F);
        tbTin.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tbTin.setName(""); // NOI18N
        tbTin.setRowHeight(20);
        tbTin.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbTinMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tbTin);

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lblTitle.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblTitle.setForeground(new java.awt.Color(0, 51, 255));
        lblTitle.setToolTipText("Tiêu đề tin tức");

        txtSummary.setBackground(new java.awt.Color(240, 240, 240));
        txtSummary.setColumns(20);
        txtSummary.setLineWrap(true);
        txtSummary.setRows(5);
        txtSummary.setWrapStyleWord(true);
        txtSummary.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        txtSummary.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        txtSummary.setDisabledTextColor(new java.awt.Color(0, 0, 102));
        txtSummary.setEnabled(false);
        jScrollPane1.setViewportView(txtSummary);

        lHinh.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(lHinh, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbNgayDang, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(31, 31, 31))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 433, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lHinh, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(lbNgayDang, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(19, 19, 19))
        );

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/TinTuc/image/gnome_view_refresh.png"))); // NOI18N
        jButton2.setText("Lấy tin");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/TinTuc/image/remove.png"))); // NOI18N
        jButton3.setText("Xóa tin");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        btnnext.setText(">");
        btnnext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnnextActionPerformed(evt);
            }
        });

        btnpre.setText("<");
        btnpre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnpreActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 512, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnpre)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lbtrang, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbtongtrang, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(2, 2, 2)
                        .addComponent(btnnext)
                        .addGap(56, 56, 56)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(btnnext)
                    .addComponent(btnpre)
                    .addComponent(lbtrang)
                    .addComponent(lbtongtrang))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jToolBar1.setRollover(true);

        btncauHinhXPath.setIcon(new javax.swing.ImageIcon(getClass().getResource("/TinTuc/image/administrative_tools.png"))); // NOI18N
        btncauHinhXPath.setText("C.h XPath");
        btncauHinhXPath.setToolTipText("Cấu hình XPath cho trang web");
        btncauHinhXPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btncauHinhXPathActionPerformed(evt);
            }
        });
        jToolBar1.add(btncauHinhXPath);

        btnThemChuyenMuc.setIcon(new javax.swing.ImageIcon(getClass().getResource("/TinTuc/image/Add.png"))); // NOI18N
        btnThemChuyenMuc.setText("Thêm Chuyên Mục");
        btnThemChuyenMuc.setToolTipText("Thêm chuyên mục vào web đã chọn");
        btnThemChuyenMuc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThemChuyenMucActionPerformed(evt);
            }
        });
        jToolBar1.add(btnThemChuyenMuc);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/TinTuc/image/remove.png"))); // NOI18N
        jButton1.setText("Xóa");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtURL, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtURL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        try {
            String url = txtURL.getText();
            String[] s = url.split("//");
            String url_ = s[1].substring(0, s[1].length() - 1);
            AddWeb(TN, url_);
            File fi = new File("data/" + url_ + ".xml");
            if (!fi.exists()) {
                ArticleWriter aw = new ArticleWriter(fi);
                aw.Write();
            }
        } catch (JDOMException ex) {
            JOptionPane.showMessageDialog(rootPane, "Lỗi dòng 431");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(rootPane, "Lỗi dòng 433");
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void tbTinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbTinMouseClicked
        // TODO add your handling code here:
        int selectedRow = tbTin.getSelectedRow();
        loadTin(ds, selectedRow);
    }//GEN-LAST:event_tbTinMouseClicked

    private void tree1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tree1MouseClicked
        // TODO add your handling code here:
        try {
            if (TN.isLeaf()) {
                lbtrang.setText("1");
                String filename = "data/" + TN.getParent().toString() + ".xml";
                File f = new File(filename);
                if (f.exists()) {
                    String chuyenmux = TN.toString();
                    ListItem(filename, chuyenmux, new int[]{1});
                    ArticleWriter aw = new ArticleWriter(f);
                    lbtongtrang.setText("/" + aw.Count(chuyenmux) + "");
                }
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_tree1MouseClicked

    private void txtURLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtURLActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtURLActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        try {
            TreePath path = tree1.getSelectionPath();
            if (path != null) {

                MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();

                JOptionPane.showMessageDialog(rootPane, "Đã xóa" + node.toString());

                MutableTreeNode parent = (MutableTreeNode) node.getParent();
                int index = parent.getIndex(node);
                parent.remove(node);

                model = (DefaultTreeModel) tree1.getModel();
                model.nodesWereRemoved(parent, new int[]{index}, null);
            }
        } catch (NullPointerException ex) {
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnThemChuyenMucActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemChuyenMucActionPerformed
        // TODO add your handling code here:
        try {
//            ChuyenMuc t=new ChuyenMuc();           
            TNout = TN;
            JLabel lb1 = new JLabel("Chuyen Muc");
            JLabel lb2 = new JLabel("URL");
            JTextField t1 = new JTextField();
            JTextField t2 = new JTextField();
            do {
                final JComponent[] in = new JComponent[]{lb1, t1, lb2, t2};
                JOptionPane.showMessageDialog(null, in, null, JOptionPane.PLAIN_MESSAGE);
                if (t1.getText().length() == 0 || t2.getText().length() == 0) {
                    JOptionPane.showMessageDialog(null, "NULL");
                }
            } while (t1.getText().length() == 0 || t2.getText().length() == 0);
            AddWeb(TN, t1.getText());
            //zzzzzzzzzzzzzz
            String web = TN.toString();
            //String a[] = web.split("//");
            //web = a[1].substring(0, a[1].length() - 1);
            File fi = new File("data/" + web + ".xml");
            ArticleWriter aw = new ArticleWriter(fi);
            aw.Write(t1.getText(), t2.getText());
        } catch (ArrayIndexOutOfBoundsException ex) {
            JOptionPane.showMessageDialog(lHinh, "Thêm Thất Bại");
        }
        //ArticleWriter aw
    }//GEN-LAST:event_btnThemChuyenMucActionPerformed

    private void btncauHinhXPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btncauHinhXPathActionPerformed
        // TODO add your handling code here:
        //JOptionPane.showMessageDialog(rootPane,TN.toString());

        ThemWeb tw = new ThemWeb();
        if (TN.isLeaf()) {
            TNout = TN.getParent();
        } else {
            TNout = TN;
        }
        if (TNout.toString().equals("Web")) {
            TNout = TN;
        }
        tw.setVisible(true);
    }//GEN-LAST:event_btncauHinhXPathActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        if (TN == null) {
            JOptionPane.showMessageDialog(rootPane, "Xin chọn web tin tức");
            return;
        }
        if (TN.isLeaf()) {
            try {

                String tenfile = TN.getParent().toString();
                File ff = new File("data/" + tenfile + ".xml");
                ArticleReader ar = new ArticleReader(ff);
                String url = ar.LayURL(TN.toString());
                convertHTML.readPage(url);
                chuyenHTMLXML.ConvertHTMLToXML("text.html", tenfile);
                String FileName = "temp/" + tenfile + ".xml";
                XPathReader xpathReader = new XPathReader(new File("cautrucxpathcuatrangweb.xml"));
                WebReader xp = new WebReader();
                xp.setKeyDomain(TN.getParent().toString());
                xp = new WebReader(FileName, "div", xpathReader, "count");
                File awFi = new File("data/" + tenfile + ".xml");
                ArticleWriter aw = new ArticleWriter(awFi);
                int n = xp.Count();
                boolean flag = false;
                boolean Trang1TonTai = ar.PageExsist(TN.toString(), 1);
                if (Trang1TonTai == false) {
                    aw.Write(TN.toString(), 1);
                }

                for (int i = 1; i <= n; i++) {
                    try {
                        xp = new WebReader(FileName, "div", i, xpathReader);
                        if (xp.getLink() != null && ArticleReader.isDuplicate(TN.toString(), xp.getLink(), awFi) == true) {
                            flag = true;
                        }

                        if (aw.Count(TN.toString(), 1) >= 15) {
                            aw.IncreasePage(TN.toString());
                            aw.Write(TN.toString(), 1);
//                            if (flag == false) {
//                                flag = true;
//                            }

                        }
                        if (flag == false) {

                            String tt = xp.getTitle().trim();
                            if (tt != null) {
                                aw.Write(TN.toString(), 1, xp.getLink().trim(), xp.getTitle(), xp.getImg(), xp.getDate(), xp.getSummary());
                                 
                            }
                        }
                        flag=false;
                    } catch (Exception ex) {
                    }
                }
                ListItem("data/" + tenfile + ".xml", TN.toString(), new int[]{1});
                JOptionPane.showMessageDialog(rootPane, "Thành Công");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(lHinh, "Loi 595");
            }

        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
        // TODO add your handling code here:
        try {
            int row = tbTin.getSelectedRow();
            String url = (String) tbTin.getValueAt(row, 1);
            JOptionPane.showMessageDialog(rootPane, url);

            File fi = new File("data/" + TN.getParent().toString() + ".xml");

            ArticleWriter aw = new ArticleWriter(fi);
            aw.Detach(TN.toString(), url);
            ((DefaultTableModel) tbTin.getModel()).removeRow(row);
            tbTin.updateUI();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(rootPane, "Chưa chọn tin");
        }
    }//GEN-LAST:event_jButton3MouseClicked

    private void btnpreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnpreActionPerformed
        // TODO add your handling code here:
        iPage--;
        if (iPage <= 0) {
            iPage = 1;
        }
        String filename = "data/" + TN.getParent().toString() + ".xml";
        File f = new File(filename);
        String chuyenmux = TN.toString();
        this.NhayTrang(filename, chuyenmux, iPage);
        lbtrang.setText(iPage + "");
    }//GEN-LAST:event_btnpreActionPerformed

    private void btnnextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnnextActionPerformed
        // TODO add your handling code here:
        iPage++;
        String filename = "data/" + TN.getParent().toString() + ".xml";
        File f = new File(filename);
        String chuyenmux = TN.toString();
        boolean kq = this.NhayTrang(filename, chuyenmux, iPage);
        if (kq == true) {
            lbtrang.setText(iPage + "");
        } else {
            JOptionPane.showMessageDialog(rootPane, "Hết tin");
            iPage--;
        }

    }//GEN-LAST:event_btnnextActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }

        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUI().setVisible(true);
            }
        });
    }
    private TreeNode TN;
    public static TreeNode TNout;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnThemChuyenMuc;
    private javax.swing.JButton btncauHinhXPath;
    private javax.swing.JButton btnnext;
    private javax.swing.JButton btnpre;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lHinh;
    private javax.swing.JLabel lbNgayDang;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JLabel lbtongtrang;
    private javax.swing.JLabel lbtrang;
    private javax.swing.JTable tbTin;
    private javax.swing.JTree tree1;
    private javax.swing.JTextArea txtSummary;
    private javax.swing.JTextField txtURL;
    // End of variables declaration//GEN-END:variables
}
